#!/bin/sh
# Author: mario manno <projects@manno.name>
# Description: measure traffic for one xen host
# Get xen host name from symlink
#
#%# family=auto
#%# capabilities=autoconf suggest


DOMAIN=$( basename $0 | sed 's/^xen_traffic_//g' )
NAME=$( echo $DOMAIN | sed -e's/-/_/g' ) 

if [ "$1" = "autoconf" ]; then
    if which xm > /dev/null ; then
        echo yes
    else
        echo "no (xm not found)"
        exit 1
    fi
    if [ -r /proc/net/dev ]; then
        echo yes
    else
        echo "no (/proc/net/dev not found)"
        exit 1
    fi
    exit 0
fi

if [ "$1" = "suggest" ]; then
    xm list | awk '{print $1}' | egrep -v "^(Name|Domain-0)"
    exit 0
fi

if [ "$1" = "config" ]; then
    echo "graph_title Xen Traffic for $NAME"
    echo 'graph_vlabel bits in (-) / out (+) per ${graph_period}'
    echo 'graph_args --base 1024 -l 0'
    echo 'graph_category xen'
    echo 'out.label sent'
    echo 'out.type DERIVE'
    echo 'out.min 0'
    echo 'out.cdef out,8,*'
    echo 'in.label received'
    echo 'in.type DERIVE'
    echo 'in.min 0'
    echo 'in.cdef in,8,*'
    exit 0
fi

dev=$( xm network-list $DOMAIN | egrep "^[0-9]+" | sed 's@^.*vif/\([0-9]*\)/\([0-9]*\).*$@vif\1.\2@')

awk -v interface="$dev" \
    'BEGIN { gsub(/\./, "\\.", interface) } \
    $1 ~ "^" interface ":" {
        split($0, a, /: */); $0 = a[2]; \
        print "in.value " $1 "\nout.value " $9 \
    }' \
    /proc/net/dev


